package com.ithao.service.impl;

import com.ithao.common.QuestionConst;
import com.ithao.dao.*;
import com.ithao.database.MmDaoException;
import com.ithao.entity.PageResult;
import com.ithao.entity.QueryPageBean;
import com.ithao.pojo.*;
import com.ithao.service.QuestionService;
import com.ithao.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @description ：题目业务实现类
 * @version: 1.0
 */
@Slf4j
@Service
@Transactional
public class QuestionServiceImpl implements QuestionService {
    @Autowired
    private QuestionDao questionDao;
    @Autowired
    private QuestionItemDao questionItemDao;
    @Autowired
    private TagDao tagDao;
    @Autowired
    private IndustryDao industryDao;
    @Autowired
    private CompanyDao companyDao;
    @Autowired
    private ReviewLogDao reiviewLogDao;
    @Autowired
    private DictDao dictDao;
    @Autowired
    private UserDao userDao;

    @Override
    public PageResult findByPage(QueryPageBean queryPageBean) {
        log.info("QuestionService findByPage:{}", queryPageBean);
        if (queryPageBean.getQueryParams() == null) {
            queryPageBean.setQueryParams(new HashMap());
        }
        //默认查询基础题库
        queryPageBean.getQueryParams().put("isClassic", 0);
        // 获取数据集
        List<Question> questionList = questionDao.selectIsClassicByPage(queryPageBean);
        // 获取总数据条数
        Long totalCount = questionDao.selectCountIsClassicByPage(queryPageBean);
        return new PageResult(totalCount, questionList);
    }

    @Override
    public void addOrUpdate(Question question) {

        log.info("QuestionService question:{}", question);
        // 1 添加题目信息
        if (addOrUpdateQuestion(question) == 0) {
            throw new MmDaoException("更新数据失败");
        }
        log.debug("QuestionService question.id:{}", question.getId());

        // 2.更新题目选项信息
        updateQuestionItemList(question);
        // 3.更新标签信息
        updateTagList(question);
        // 4.更新公司信息(行业信息)
        updateCompany(question);
        // 提交保存
        log.debug("dao question:{}", question);


    }

    // 新增或更新题目
    private Integer addOrUpdateQuestion(Question question) {
        log.info("QuestionService addOrUpdateQuestion:{}", question);
        Integer result = 0;
        question.setCompanyId(question.getCompany().getId());
        if (question.getId() == null || question.getId() == 0) {
            // 初始化题目相关信息
            question.setCreateDate(DateUtils.parseDate2String(new Date()));
            // 通过枚举下标，获取的值对应数据需要的值
            // 初始化题目状态及审核状态
            question.setStatus(QuestionConst.Status.PRE_PUBLISH.ordinal()); //初始化题目状态 0 待发布
            question.setReviewStatus(QuestionConst.ReviewStatus.PRE_REVIEW.ordinal()); //初始化审核状态 0 待审核
            question.setIsClassic(0); //新增题目为基础题目
            result = questionDao.add(question);
        } else {
            result = questionDao.update(question);
        }
        return result;
    }

    // 更新题目选项信息
    private void updateQuestionItemList(Question question) {
        log.info("QuestionService updateQuestionItemList:{}", question.getQuestionItemList());
        for (QuestionItem questionItem : question.getQuestionItemList()) {
            // 设置应对的题目ID
            questionItem.setQuestionId(question.getId());
            if (questionItem.getContent() == null || questionItem.getContent().length() == 0) {
                if (questionItem.getImgUrl() == null || questionItem.getImgUrl().length() == 0)
                    continue;
            }
            if (questionItem.getId() == null || questionItem.getId() == 0) {
                // 新增
                questionItemDao.addQuestionItem(questionItem);
            } else {
                // 更新
                questionItemDao.updateQuestionItem(questionItem);
            }
        }
    }

    // 更新标签信息
    private void updateTagList(Question question) {
        log.info("QuestionService updateTagList:{}", question.getTagList());
        // 删除之前的题目标签关系
        tagDao.deleteTagByQuestionId(question.getId());
        for (Tag tag : question.getTagList()) {
            Map<String, Object> mapQuestionTag = new HashMap<>();
            mapQuestionTag.put("questionId", question.getId());
            Integer tagId = 0;
            // 新增标签
            if (tag.getId() == 0) {
                tag.setStatus(QuestionConst.TagStatus.ENABLE.ordinal());
                tag.setUserId(question.getUserId());
                tag.setCreateDate(DateUtils.parseDate2String(new Date()));
                tag.setCourseId(question.getCourseId());
                tagDao.addTag(tag);
            }
            mapQuestionTag.put("tagId", tag.getId());
            tagDao.addTagByQuestionId(mapQuestionTag);
        }
    }

    // 更新公司信息
    private void updateCompany(Question question) {
        log.info("QuestionService updateCompany:{}", question.getCompany());
        Company company = question.getCompany();
        // 更新城市关系
        company.setUserId(question.getUserId());
        companyDao.updateCompanyCity(company);
        // 删除旧企业方向关系
        companyDao.deleteCompanyIndustryByCompanyId(company.getId());
        // 新增新的行业方向及关系
        List<Industry> industryList = company.getIndustryList();
        for (Industry industry : industryList) {
            Map<String, Object> one = new HashMap<>();
            one.put("companyId", company.getId());
            if (industry.getId() == 0) {
                // 新增行业方向
                industryDao.add(industry);
            }
            one.put("industryId", industry.getId());
            companyDao.addCompanyIndustry(one);
        }
    }

    @Override
    public PageResult findClassicByPage(QueryPageBean queryPageBean) {
        log.info("QuestionService findClassicByPage:{}", queryPageBean);
        if (queryPageBean.getQueryParams() == null) {
            queryPageBean.setQueryParams(new HashMap());
        }
        // 查询精选题目
        queryPageBean.getQueryParams().put("isClassic", 1);
        List<Question> questionList = questionDao.selectIsClassicByPage(queryPageBean);
        // 获取每条记录的审核状态
        for (Question question : questionList) {
            ReviewLog reviewLog = reiviewLogDao.selectLastByQuestionId(question.getId());
            if (reviewLog == null) {
                reviewLog = new ReviewLog();
                reviewLog.setStatus(0);
                reviewLog.setComments("");
                reviewLog.setReviewer("");
                reviewLog.setCreateDate("");
            }
            User user = userDao.findById(reviewLog.getUserId());
            if (null != user) {
                reviewLog.setReviewer(user.getUsername());
            }
            question.setReviewLog(reviewLog);
        }
        // 获取总记录数
        Long totalCount = questionDao.selectCountIsClassicByPage(queryPageBean);
        return new PageResult(totalCount, questionList);
    }

    @Override
    public void updateIsClassic(Integer questionId, Integer isClassic) {
        Integer result = questionDao.updateIsClassic(questionId, isClassic);
        if (result == 0) {
            throw new MmDaoException("更新经典题目失败");
        }
    }

    @Override
    public Question findQuestionById(Integer id) {
        log.info("QuestionService findQuestionById:{}", id);
        // 获取题目基本信息
        // 级联获取题目选项信息
        Question question = questionDao.selectById(id);
        log.debug("question:{}", question);
        // 获取所属标签名称列表
        initQuestionTag(question);
        // 根据公司ID，获取所属公司信息
        initQuestionCompany(question);
        return question;
    }

    @Override
    public void delete(Integer id) {
        //TODO 先删中间表
        //删题目选项
        questionItemDao.deleteByQuestionId(id);
        //删题目便签中间表
        tagDao.deleteTagByQuestionId(id);
        //删题目的审核记录表
        if (reiviewLogDao.selectLastByQuestionId(id) != null) {
            reiviewLogDao.deleteBuQuestionId(id);
        }
        //最后删题
        questionDao.delete(id);
    }

    /**
     * 下架
     *
     * @param id
     */
    @Override
    public void down(Integer id) {
        questionDao.down(id);
    }

    // 获取题目标签信息
    private void initQuestionTag(Question question) {
        log.info("QuestionService initQuestionTag:{}", question.getId());
        List<Tag> tagList = tagDao.selectTagListByQuestionId(question.getId());
        List<String> tagNameList = new ArrayList<>();
        for (Tag one : tagList) {
            tagNameList.add(one.getName());
        }
        // 设置标签名称列表
        question.setTagNameList(tagNameList);
        question.setTagList(tagList);
    }

    // 获取题目公司及行业信息
    private void initQuestionCompany(Question question) {
        log.info("QuestionService initQuestionCompany:{}", question.getCompanyId());
        Company company = companyDao.findById(question.getCompanyId());
        if (company == null) {
            return;
        }
        Dict dict = dictDao.findById(company.getCityId());
        if (dict == null) {
            return;
        }
        company.setCity(dict.getDataValue());
        // 根据公司ID，获取所属行业信息
        List<Industry> industryList = industryDao.selectIndustryListByCompany(question.getCompanyId());
        if (industryList != null && industryList.size() > 0) {
            List<String> industryNameList = new ArrayList<>();
            for (Industry one : industryList) {
                industryNameList.add(one.getName());
            }
            company.setIndustryNameList(industryNameList);
            company.setIndustryList(industryList);
        }
        // 设置所属公司(包含所属城市行业)
        question.setCompany(company);
    }
}
